import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


//回显服务器
public class UdpEchoClient {
    private DatagramSocket socket = null;

    //端口被占用会报异常
    public UdpEchoClient(int id) throws SocketException {
        socket = new DatagramSocket(id);
    }

    public  void stack() throws IOException {
        System.out.println("服务器启动!");
        while(true) {
            //1.读取客服端的请求
            DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
            socket.receive(packet);

            //2.解析请求
            String str1 = new String(packet.getData(), 0, packet.getLength());

            //3.根据请求回应
            String str2 = Process(str1);

            //4.构建响应数据
            //(1)获取字符串的字符数组
            //(2)获取字符数组的长度
            //(3)获取发送方的端口号+IP(接收了Socket的数据本身就包含端口号和IP)
            DatagramPacket packet1 = new DatagramPacket(str2.getBytes(), str2.getBytes().length, packet.getSocketAddress());

            //5.返回响应数据
            socket.send(packet1);

            //打印信息
            System.out.printf("[%s:%d] 请求=%s;响应=%s\n", packet.getAddress().toString(), packet.getPort(), str1, str2);
        }

    }

    public String Process(String str1) {
        return str1;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient UDP = new UdpEchoClient(2000);
        UDP.stack();
    }
}
